package com.lalilu.homework9.fragment;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lalilu.homework9.R;
import com.lalilu.homework9.service.MusicService2;

import org.jetbrains.annotations.NotNull;


public class MusicFragment2 extends Fragment {
    public MyConn myConn;

    public static class MyConn implements ServiceConnection {
        public MusicService2.MyBinder myBinder = null;

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MusicService2.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Intent intent = new Intent(requireActivity(), MusicService2.class);
        requireActivity().startService(intent);
        if (myConn == null) {
            myConn = new MyConn();
            requireActivity().bindService(intent, myConn, 0);
        }

        Button _start = view.findViewById(R.id.music_start_2);
        Button _next = view.findViewById(R.id.music_next);
        Button _end = view.findViewById(R.id.music_stop_2);

        _start.setOnClickListener(v -> myConn.myBinder.play());
        _next.setOnClickListener(v -> myConn.myBinder.next());
        _end.setOnClickListener(v -> myConn.myBinder.destroy());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_music2, container, false);
    }
}